package org.nhindirect.stagent;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class HeaderCollection extends ObjectCollection<Header> 
{
    public HeaderCollection()
    {                
    }
    
    public HeaderCollection(Collection<Header> headers)
    {
    	super(headers);
    }
    
    public Header getHeader(String name)
    {
    	for (Header header : this)
    		if (header.getName().compareToIgnoreCase(name) == 0)
    			return header;
    			
    	return null;
    }
    

    
    public void setHeader(String name, Header value)
    {
        int currentIndex = this.indexOf(name);
        if (currentIndex < 0)
        {
            this.add(value);
            return;
        }
        
        if (value == null)
        {
            this.remove(currentIndex);
            return;
        }
        
        this.setItem(currentIndex, value);
    }
    
    public Collection<Header> getMimeHeaders()
    {
    	List<Header> retVal = new ArrayList<Header>();
    	
    	for (Header header : this)
    		if (Protocol.startsWith(header.getName(), Protocol.MimeHeaderPrefix))
    			retVal.add(header);

    	return retVal;
    }
    
    public Collection<Header> getNonMimeHeaders()
    {
    	List<Header> retVal = new ArrayList<Header>();
    	
    	for (Header header : this)
    		if (!Protocol.startsWith(header.getName(), Protocol.MimeHeaderPrefix))
    			retVal.add(header);

    	return retVal;    	

    }
    
    public int indexOf(String name)
    {
        if (name == null || name.length() == 0)
        {
            throw new IllegalArgumentException();
        }
        
        for (int i = 0, count = this.size(); i < count; ++i)
        {
            if (this.get(i).getName().compareToIgnoreCase(name) == 0)
            {
                return i;
            }
        }            
        
        return -1;
    }
    
    public void addUpdate(Collection<Header> headers)
    {
        if (headers == null)
        {
            throw new IllegalArgumentException();
        }
        
        for (Header header : headers)
        {
        	this.setHeader(header.getName(), header);
        }
    }
    
    public HeaderCollection selectMimeHeaders()
    {
        return new HeaderCollection(this.getMimeHeaders());
    }

    public HeaderCollection selectNonMimeHeaders()
    {
        return new HeaderCollection(this.getNonMimeHeaders());
    }

}
